import { StorageUtil } from '@/utils/storage';
import type { Commit } from 'vuex';
import type { SystemState, SystemMutations, SystemActions, SystemGetters } from './system.type';

const state: SystemState = {
  systemInfo: null,
};

const mutations: SystemMutations = {
  SET_SYSTEM_INFO: (state: SystemState, value: any) => {
    state.systemInfo = value;
  },
};

const actions: SystemActions = {
  SystemInfo({ commit, state }: { commit: Commit; state: SystemState }) {
    return new Promise((resolve, reject) => {
      if (state.systemInfo) {
        resolve(state.systemInfo);
      } else {
        uni.getSystemInfo({
          success(res: any) {
            commit('SET_SYSTEM_INFO', res);
            StorageUtil.setLocalStorage('SYSTEM_INFO', res, 86400);
            resolve(res);
          },
          fail(err: any) {
            reject(err);
          },
        });
      }
    });
  },
};

const getters: SystemGetters = {
  getSystemInfo: (state: SystemState) => {
    if (state.systemInfo) {
      return state.systemInfo;
    } else if (StorageUtil.getLocalStorage('SYSTEM_INFO')) {
      return JSON.parse(StorageUtil.getLocalStorage('SYSTEM_INFO'));
    }
    return {};
  },
};

export default {
  state,
  mutations,
  actions,
  getters
};